import { Injectable } from '@angular/core';
import { concat, Observable, of, zip } from 'rxjs';
import { map, switchMap, tap } from 'rxjs/operators';
import {
  OpscopeService,
  Pageable,
  PageableObject,
  SysroleService,
} from 'sparrow-permission-lib';
import { NzTableGetdata } from './nz-table-getdata';

@Injectable({
  providedIn: 'root',
})
export class NzTableGetdataScopeService implements NzTableGetdata {
  constructor(
    private scopeService: OpscopeService,
    private sysroleService: SysroleService
  ) {}
  getPagedData(pageable: Pageable): Observable<any> {
    let resMain: any;
    const scopes$ = this.scopeService.all3(pageable).pipe(
      tap((res) => (resMain = res)),
      map((res: any) => res.content),
      switchMap((scopes: any[]) => {
        return zip(...scopes.map((scope: any) => this.getSysroles(scope)));
      }),
      map((res) => {
        resMain.content = res;
        return resMain;
      }),
      tap((ssss) => console.log(ssss)),
    );
    return scopes$;
  }

  getSysroles(scope: any) {
    return this.scopeService
      .getPermissions(scope.id, { page: 0, size: 10000 })
      .pipe(
        map((sysroleScopes: any) => sysroleScopes.content),
        switchMap((sysroleScopes) =>
          sysroleScopes.length === 0
            ? of([])
            : zip(
                ...sysroleScopes.map((sysroleScope: any) =>
                  this.sysroleService.get1(sysroleScope.id.sysroleId)
                )
              )
        ),
        map((sysroles) => Object.assign(scope,{sysroles: sysroles})
        )
      );
  }
}
